package pers.ht.mbpo.service;

import net.sf.json.JSONArray;
import pers.ht.mbpo.bean.Notice;
import pers.ht.mbpo.dao.NoticeDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/NoticeServlet")
public class NoticeServlet extends HttpServlet {
    private NoticeDao noticeDao = new NoticeDao();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String action = request.getParameter("action");
        if ("insert".equals(action)){
            noticeDao.insert(new Notice(request.getParameter("noticeTitle"),request.getParameter("noticeDesc")));
            response.sendRedirect("NoticeServlet?action=query");
        }
        if ("update".equals(action)){
            noticeDao.edit(new Notice(Integer.parseInt(request.getParameter("noticeId")),request.getParameter("noticeTitle"),request.getParameter("noticeDesc")));
            response.sendRedirect("NoticeServlet?action=query");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        if("query".equals(action)){
            List<Notice> notices = noticeDao.query();
            String noticeJson = JSONArray.fromObject(notices).toString();
            request.setAttribute("noticeJson",noticeJson);
            request.getRequestDispatcher("admin/notice.jsp").forward(request, response);
        }
        if ("delete".equals(action)){
            String noticeId = request.getParameter("noticeId");
            noticeDao.delete(noticeId);
            response.sendRedirect("NoticeServlet?action=query");
        }
        if ("find".equals(action)){
            String noticeId = request.getParameter("noticeId");
            Notice notice = noticeDao.queryOne(noticeId);
            request.setAttribute("notice",notice);
            request.setAttribute("flag",true);
            request.getRequestDispatcher("admin/AENotice.jsp").forward(request, response);
        }
        if ("add".equals(action)) {
            request.getRequestDispatcher("admin/AENotice.jsp").forward(request, response);
        }
    }
}
